home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8555 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  46 lines

  1. Newsgroups: comp.lang.c++
  2. Path: in1.uu.net!allegra!alice!ark
  3. From: ark@research.att.com (Andrew Koenig)
  4. Subject: Re: Does this create memory leak?...
  5. Message-ID: <DMxDwy.J80@research.att.com>
  6. Organization: AT&T Research, Murray Hill NJ
  7. References: <3123DF68.1677@sierra.net>
  8. Date: Sat, 17 Feb 1996 15:05:21 GMT
  9.  
  10. In article <3123DF68.1677@sierra.net> T Colwell <snowbull@sierra.net> writes:
  11.  
  12. > The code which follows seams like it would create a memory leak.
  13.  
  14. It does.  See below.
  15.  
  16. >   CAT CAT::operator=(const CAT & rhs)
  17. >   {
  18. >      if (this == &rhs)
  19. >         return *this;
  20. >         itsAge = new int;
  21. >         itsWeight = new int;
  22. >         *itsAge = rhs.GetAge();
  23. >         *itsWeight = rhs.GetWeight();
  24. >   }
  25.  
  26. The indentaion is a little funny here, and you don't return a value in the
  27. normal case.  Moreover, you don't delete the old values, which causes
  28. a memory leak, and you return a copy of the object, which in this case
  29. cannot be right because you didn't define a copy constructor.  How about this:
  30.  
  31.     CAT& CAT::operator=(const CAT & rhs)
  32.     {
  33.         if (this != &rhs) {
  34.             delete itsAge;
  35.             delete itsWeight;
  36.             itsAge = new int(rhs.GetAge());
  37.             itsWeight = new int(rhs.GetWeight());
  38.         }
  39.         return *this;
  40.     }
  41.  
  42. Next you have to define a copy constructor, which is left as an exercise.
  43. -- 
  44.                 --Andrew Koenig
  45.                   ark@research.att.com
  46.